package com.kerwin.project.base;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.kerwin.project.videolist.entity.KVideo;

/**
 * 基类,用于放一些通用的方法
 * @author KERWIN
 *
 */
@Service("projectBaseService")
public class ProjectBaseService {
	
	Logger logger = Logger.getLogger(ProjectBaseService.class);
	
	/**
	 * 文件上传
	 * @param request
	 * @param realPath	//上传的路径
	 * @param path	//文件上传在项目中的路径      /images/video/videoPoster
	 * @return 文件名
	 */
	public KVideo uploadFile(HttpServletRequest request, String realPath, String path){
		KVideo video = new KVideo();
		File file = new File(realPath);
		if(!file.exists() && !file.isDirectory()){
			logger.info("目录:'" + realPath + "' 不存在,重新创建!");;
			file.mkdir();
		}
		//创建文件上传工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//创建一个文件上传解析器
		ServletFileUpload upload = new ServletFileUpload(factory);
		//解决上传文件名的中文乱码
		upload.setHeaderEncoding("UTF-8");
		InputStream inputStream = null;
		FileOutputStream fileOutputStream = null;
		String fileName = null;
		try {
			List<FileItem> fileItemList = upload.parseRequest(request);
			for(FileItem fileItem : fileItemList){
				if(!fileItem.isFormField()){	//上传文件
					//得到上传的文件名称
					fileName = fileItem.getName();
					if(null == fileName || fileName.trim().equals("")){
						continue;
					}
					//得到上传的文件的后缀
					String[] names = fileName.split("\\.");
					if(null != names && names.length > 0){
						fileName = names[names.length - 1];
					}else{
						return null;
					}
					//用当前时间戳保证上传名称唯一
					fileName = Calendar.getInstance().getTimeInMillis() + "." + fileName;
					video.setVideoPoster(".." + path + "/" + fileName);
					//获取上传文件的输入流
					inputStream = fileItem.getInputStream();
					//创建一个文件输出流
					fileOutputStream = new FileOutputStream(realPath + "\\" + fileName);
					//创建一个缓冲区
					byte buffer[] = new byte[1024];
					//判断输入流中的数据是否已经读完的标识
					int len = 0;
					//循环将输入流读入到缓冲区中,(len = inputStream.read(buffer)) > 0,
					//表示inputStream中还有数据
					while((len = inputStream.read(buffer)) > 0){
						//使用FileOutputStream输出流,将缓冲区中的数据写入到指定目录
						fileOutputStream.write(buffer, 0, len);
					}
					//删除文件上传时产生的临时文件
					fileItem.delete();
				}else{	//普通输入项
					String name = fileItem.getFieldName();
					String value = fileItem.getString("UTF-8");	//解决中文乱码
					if("videoName".equals(name)){
						video.setVideoName(value);
					}else if("videoAbout".equals(name)){
						video.setVideoAbout(value);
					}else if("onlineAddr".equals(name)){
						video.setOnlineAddr(value);
					}else if("downloadAddr".equals(name)){
						video.setDownloadAddr(value);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("上传文件失败", e);
			return null;
		}finally{
			try {
				if(null != inputStream){					
					inputStream.close();
				}
				if(null != fileOutputStream){					
					fileOutputStream.close();
				}
			} catch (IOException e) {
				logger.debug("IO流关闭失败!", e);
				e.printStackTrace();
			}
		}
		return video;
	}
}
